// 该文件用于创建Vuex中最核心的store
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)

const countOptions = {
    namespaced: true,
    actions: {
        jiaOdd: function (context, value) {
            if (context.state.sum % 2) {
                context.commit('JIA', value)
            }
        },
        jiaWait: function (context, value) {
            setTimeout(() => {
                // context.commit('JIA', value)
            }, 500);
            context.commit('JIA', value)
        }
    },
    mutations: {
        JIA: function (state, value) {
            state.sum += value
        },
        JIAN: function (state, value) {
            state.sum -= value
        },
    },
    state: {
        sum: 1,
        school: "尚硅谷",
        subject: "前端",
    },
    getters: {
        bigSum(state) {
            return state.sum * 10
        }
    },
}

const personOptions = {
    namespaced: true,
    actions: {
        addPersonWang: function (context, personObj) {
            if (personObj.name.indexOf('王') === 0) {
                context.commit('ADD_PERSON', personObj)
            }else{
                alert("这个按钮只能添加姓王的人")
            }
        }
    },
    mutations: {
        ADD_PERSON(state, personObj) {
            if (personObj.name !== '') {
                state.personList.unshift(personObj)
            }
        }
    },
    state: {
        personList: [
            { id: "001", name: "张三" },
        ],
    },
    getters: {
        // 比如我现在在personOptions里，那这个state就是它自己的state，不需要state.state.personList
        firstPersonName: function (state) {
            return state.personList[0].name
        }
    },
}

// 创建 store
export default new Vuex.Store({
    modules: {
        count: countOptions,
        person: personOptions,
    }
})